package org.example.main.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.example.main.utils.CommonResult;
import org.example.main.entity.Admin;
import org.example.main.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.example.main.utils.KeyUtils;
import org.example.main.utils.Sm2Util;

@CrossOrigin
@Tag(name = "管理员管理",description = "管理员管理相关接口")
@RestController
@RequestMapping("/admin")
public class AdminController {
    private static final Logger logger = Logger.getLogger(AdminController.class);

    @Autowired
    private AdminService adminService;

    @Operation(summary = "管理员注册")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "注册成功"),
            @ApiResponse(responseCode = "400", description = "用户名已存在"),
            @ApiResponse(responseCode = "500", description = "注册失败")

    })
    @PostMapping("/register")//http://localhost:8089/main/admin/register
    public CommonResult register(@RequestBody Admin admin) {
        CommonResult commonResult = new CommonResult();
        try {
            Admin existing = adminService.findByUsername(admin.getUsername());
            if (existing != null) {
                commonResult.setCode(400);
                commonResult.setMsg("用户名已存在");
            }
            else {
                // 生成SM2密钥对
                Map<String, String> keyPair = KeyUtils.generateSmKey();
                String publicKeyStr = keyPair.get(KeyUtils.PUBLIC_KEY);
                String privateKeyStr = keyPair.get(KeyUtils.PRIVATE_KEY);

                // 保存公钥和私钥
                admin.setPublicKey(publicKeyStr);
                admin.setPrivateKey(privateKeyStr);

                adminService.add(admin);
                commonResult.setCode(200);
                commonResult.setMsg("注册成功");
                Admin current = adminService.findByUsername(admin.getUsername());
                commonResult.setData(current);
            }
        }catch (Exception e) {
            commonResult.setCode(500);
            commonResult.setMsg("注册失败");
        }
        return commonResult;
    }

    @Operation(summary = "管理员登录")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "登录成功"),
            @ApiResponse(responseCode = "401", description = "用户名或密码错误"),
            @ApiResponse(responseCode = "500", description = "登录失败")
    })
    @PostMapping("/login")//http://localhost:8089/main/admin/login
    public CommonResult login(@RequestBody Admin admin) {
        CommonResult commonResult = new CommonResult();
//        try{
//            Admin real = adminService.findByUsername(admin.getUsername());
//            if (real == null || !real.getPassword().equals(admin.getPassword())) {
//                commonResult.setCode(401);
//                commonResult.setMsg("用户名或密码错误");
//            } else {
//                commonResult.setCode(200);
//                commonResult.setMsg("登录成功");
//                commonResult.setData(real);
//            }
//        }catch (Exception e) {
//            commonResult.setCode(500);
//            commonResult.setMsg("登陆失败");
//        }
        try {
            Admin real = adminService.findByUsername(admin.getUsername());
            if (real == null) {
                commonResult.setCode(401);
                commonResult.setMsg("用户名或密码错误");
                return commonResult;
            }

            // 获取用户的公钥和私钥
            String publicKeyStr = real.getPublicKey();
            String privateKeyStr = real.getPrivateKey();

            if (publicKeyStr == null || privateKeyStr == null) {
                logger.warn("用户未设置SM2密钥对: " + admin.getUsername());
                commonResult.setCode(500);
                commonResult.setMsg("用户密钥信息不完整");
                return commonResult;
            }

            // 将Base64字符串转换为公钥和私钥对象
            PublicKey publicKey = KeyUtils.createPublicKey(publicKeyStr);
            PrivateKey privateKey = KeyUtils.createPrivateKey(privateKeyStr);

            if (publicKey == null || privateKey == null) {
                logger.error("密钥转换失败: " + admin.getUsername());
                commonResult.setCode(500);
                commonResult.setMsg("密钥解析失败");
                return commonResult;
            }

            // 使用SM2公钥加密用户提交的密码
            byte[] encryptedPasswordBytes = Sm2Util.encrypt(
                    admin.getPassword().getBytes(), publicKey);

            if (encryptedPasswordBytes == null) {
                logger.error("SM2加密失败: " + admin.getUsername());
                commonResult.setCode(500);
                commonResult.setMsg("密码加密失败");
                return commonResult;
            }

            // 使用SM2私钥解密得到原始密码
            byte[] decryptedPasswordBytes = Sm2Util.decrypt(
                    encryptedPasswordBytes, privateKey);

            if (decryptedPasswordBytes == null) {
                logger.error("SM2解密失败: " + admin.getUsername());
                commonResult.setCode(500);
                commonResult.setMsg("密码解密失败");
                return commonResult;
            }

            // 将解密后的密码与数据库中的密码进行比较
            String decryptedPassword = new String(decryptedPasswordBytes);
            if (decryptedPassword.equals(real.getPassword())) {
                commonResult.setCode(200);
                commonResult.setMsg("登录成功");
                commonResult.setData(real);
            } else {
                commonResult.setCode(401);
                commonResult.setMsg("用户名或密码错误");
            }
        } catch (Exception e) {
            logger.error("管理员登录失败", e);
            commonResult.setCode(500);
            commonResult.setMsg("登录失败");
        }
        return commonResult;
    }

    @Operation(summary = "修改管理员记录")
    @ApiResponses({
            @ApiResponse(responseCode = "200",description = "修改成功"),
            @ApiResponse(responseCode = "500",description = "修改失败")
    })
    //修改数据
    @PutMapping("/updateById")//http://localhost:8089/main/damin/updateById
    public CommonResult updateById(@RequestBody Admin admin) {
        CommonResult commonResult = new CommonResult();
        try {
            adminService.updateById(admin);
            commonResult.setCode(200);
            commonResult.setMsg("修改成功");
        }
        catch (Exception e) {
            commonResult.setCode(500);
            commonResult.setMsg("修改失败"+e.getMessage());
        }
        return commonResult;
    }

    @Operation(summary = "删除管理员记录")
    @ApiResponses({
            @ApiResponse(responseCode = "200",description = "删除成功"),
            @ApiResponse(responseCode = "500",description = "删除失败")
    })
    @DeleteMapping("/delete/{adminId}")//http://localhost:8089/main/admin/delete/{adminId}
    public CommonResult deleteById(@PathVariable long adminId) {
        CommonResult commonResult = new CommonResult();
        try{
            adminService.deleteById(adminId);
            commonResult.setCode(200);
            commonResult.setMsg("删除成功");
        }catch (Exception e) {
            commonResult.setCode(500);
            commonResult.setMsg("删除失败");
        }
        return commonResult;
    }

    @Operation(summary = "查询所有")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "404", description = "未查询到"),
            @ApiResponse(responseCode = "500", description = "查询错误")
    })
    @GetMapping("/findAll")//http://localhost:8089/main/admin/findAll
    public CommonResult findAll() {
        CommonResult commonResult = new CommonResult();
        try{
            List<Admin> admins = adminService.findAll();
            if(admins == null){
                commonResult.setCode(404);
                commonResult.setMsg("未查询到");
            }else {
                commonResult.setCode(200);
                commonResult.setMsg("查询成功");
                commonResult.setData(admins);
            }
        }catch (Exception e) {
            commonResult.setCode(500);
            commonResult.setMsg("查询失败");
        }
        return commonResult;
    }

    @Operation(summary = "按id查询")
    @ApiResponses({
            @ApiResponse(responseCode = "200",description = "查询成功"),
            @ApiResponse(responseCode = "500",description = "查询失败"),
            @ApiResponse(responseCode = "404",description = "未查询到")
    })
    @GetMapping("/findById/{adminId}")//http://localhost:8089/main/admin/findById/{adminId}
    public CommonResult findById(@PathVariable long adminId) {
        CommonResult commonResult = new CommonResult();
        try{
            Admin admin=adminService.findById(adminId);
            if(admin!=null){
                commonResult.setCode(200);
                commonResult.setMsg("查询成功");
                commonResult.setData(admin);
            }
            else{
                commonResult.setCode(404);
                commonResult.setMsg("未查询到");
            }
        }catch (Exception e){
            commonResult.setCode(500);
            commonResult.setMsg("查询失败");
        }
        return commonResult;
    }

}
